package com.ezerg.solr;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Before;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.ezerg.jdbc.DruidDatasource;

public class LuceneManager {

	JdbcTemplate jdbc = null;

	@Before
	public void before() {
		jdbc = new JdbcTemplate(DruidDatasource.getDataSource());
	}

	@Test
	public void testAddindex() throws Exception {
		// 指定索引库的存放位置Directory对象
		Directory directory = FSDirectory.open(new File("E:\\temp\\index"));
		// 索引库还可以存放到内存中
		// Directory directory = new RAMDirectory();
		// 指定一个标准分析器，对文档内容进行分析
		Analyzer analyzer = new IKAnalyzer();//StandardAnalyzer();
		// 创建indexwriterCofig对象
		// 第一个参数： Lucene的版本信息，可以选择对应的lucene版本也可以使用LATEST
		// 第二根参数：分析器对象
		IndexWriterConfig config = new IndexWriterConfig(Version.LATEST,
				analyzer);
		// 创建一个indexwriter对象
		IndexWriter indexWriter = new IndexWriter(directory, config);
		//
		String sql = "SELECT id, hotelname, address FROM itrip_hotel";
		List<Map<String, Object>> queryForList = jdbc.queryForList(sql);
		Iterator<Map<String, Object>> iterator = queryForList.iterator();
		System.out.println(queryForList.size() + "-" + iterator.hasNext());
		while (iterator.hasNext()) {
			Map<String, Object> map = (Map<String, Object>) iterator.next();
	         //创建document对象
	         Document document = new Document();	         
	         //创建field对象，将field添加到document对象中
	         //创建文件名域
	         //第一个参数：id
	         //第二个参数：酒店
	         //第三个参数：地址
	         //文件id
	         long id = (Long)map.get("id");
	         Field idField = new LongField("id", id, Store.YES);
	         //：酒店
	         String hotelname  = (String)map.get("hotelname");
	         Field hotelnameField = new TextField("hotelname", hotelname, Store.YES);	         
	 		 System.out.println("hotelname=" + hotelname);
	         //：地址（不分析、不索引、只存储）
	         String address  = (String)map.get("address");
	         Field addressField = new StoredField("address", address);	         
	         //
	         document.add(idField);
	         document.add(hotelnameField);
	         document.add(addressField);
	         //使用indexwriter对象将document对象写入索引库，此过程进行索引创建。并将索引和document对象写入索引库。
	         indexWriter.addDocument(document);			
		}
	    //关闭IndexWriter对象。
	    indexWriter.close();		
	}
	
	@Test
	public void testSearch() throws Exception {
		//创建一个Directory对象，指定索引库存放的路径
		Directory directory = FSDirectory.open(new File("E:\\temp\\index"));
		//创建IndexReader对象，需要指定Directory对象
		IndexReader indexReader = DirectoryReader.open(directory);
		//创建Indexsearcher对象，需要指定IndexReader对象
		IndexSearcher indexSearcher = new IndexSearcher(indexReader);
		 //可以指定默认搜索的域是多个
		 String[] fields = {"hotelname"/*, "address"*/};
		 //创建一个MulitFiledQueryParser对象
		 MultiFieldQueryParser queryParser = new MultiFieldQueryParser(fields, new IKAnalyzer());
		 Query query = queryParser.parse("深圳");
		 System.out.println(query);
		 //执行查询
		 //第一个参数是查询对象，第二个参数是查询结果返回的最大值
		 TopDocs topDocs = indexSearcher.search(query, 10);
		 //查询结果的总条数
		 System.out.println("查询结果的总条数："+ topDocs.totalHits);
		 //遍历查询结果
		 //topDocs.scoreDocs存储了document对象的id
		 //ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		 for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
		     //scoreDoc.doc属性就是document对象的id
		     //int doc = scoreDoc.doc;
		     //根据document的id找到document对象
		     Document document = indexSearcher.doc(scoreDoc.doc);
		     //文件名称
		     System.out.println(document.get("id"));
		     //文件内容
		     System.out.println(document.get("hotelname"));
		     //文件大小
		     System.out.println(document.get("address"));
		     System.out.println("----------------------------------");
		 }
		 //关闭indexreader对象
		 indexReader.close();

	}

}
